package org.mozhu.simple.rpc.server;

import lombok.extern.slf4j.Slf4j;

import java.util.Properties;

@Slf4j
public class RpcServerStarter {
    private RpcServer server;

    public RpcServerStarter(RpcServerConfig serverConfig) {
        server = new RpcServer(serverConfig);
    }

    private static Properties getPropsFromArgs(String[] args) {
        return new Properties();
    }

    public static void main(String[] args) {
        try {
            Properties props = getPropsFromArgs(args);
            RpcServerConfig rpcServerConfig = RpcServerConfig.fromProps(props);
            RpcServerStarter rpcServerStarter = new RpcServerStarter(rpcServerConfig);
            // attach shutdown handler to catch control-c
            Runtime.getRuntime().addShutdownHook(new Thread(() -> rpcServerStarter.shutdown()));

            rpcServerStarter.startup();
            rpcServerStarter.awaitShutdown();
        } catch (Throwable t) {
            t.printStackTrace();
            System.exit(1);
        }
        System.exit(0);
    }

    private void awaitShutdown() {
        server.awaitShutdown();
    }

    private void startup() {
        try {
            server.startup();
        } catch (Throwable t) {
            log.error("Fatal error during RpcServerStarter startup. Prepare to shutdown", t);
            System.exit(1);
        }
    }

    private void shutdown() {
        try {
            server.shutdown();
        } catch (Throwable t) {
            log.error("Fatal error during RpcServerStarter shutdown. Prepare to halt", t);
            Runtime.getRuntime().halt(1);
        }
    }

}
